package org.dromara.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.web.domain.SysJob;
import org.dromara.web.domain.bo.SysJobBo;
import org.dromara.web.domain.vo.SysJobVo;
import org.dromara.web.mapper.JobMapper;
import org.dromara.web.service.JobService;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 定时任务主Service业务层处理
 *
 * @author Zou
 * @date 2025-05-01
 */
@RequiredArgsConstructor
@Service
@Slf4j
@EnableScheduling
public class JobServiceImpl implements JobService {

    private static final String INVALID_CRON = "0 0 0 30 2 ?"; // 永不触发的合法表达式
    private String cronExpression; // 用于动态存储Cron表达式
    private final JobMapper baseMapper;
    private final TaskScheduler2 taskScheduler;
    private final ApplicationContext applicationContext;  // 注入Spring上下文来获取动态的Service
    private final jobStatusServiceImpl jobStatusServiceImpl;

    /**
     * 查询定时任务
     *
     * @param id 主键
     * @return 定时任务
     */
    @Override
    public SysJobVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询定时任务列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 定时任务分页列表
     */
    @Override
    public TableDataInfo<SysJobVo> queryPageList(SysJobBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysJob> lqw = buildQueryWrapper(bo);
        Page<SysJobVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysJob> buildQueryWrapper(SysJobBo bo) {
        LambdaQueryWrapper<SysJob> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SysJob::getJobId);
        lqw.eq(StringUtils.isNotBlank(bo.getJobName()), SysJob::getJobName, bo.getJobName());
        lqw.eq(StringUtils.isNotBlank(bo.getJobGroup()), SysJob::getJobGroup, bo.getJobGroup());
        lqw.eq(StringUtils.isNotBlank(bo.getMethodName()), SysJob::getMethodName, bo.getMethodName());
        lqw.eq(StringUtils.isNotBlank(bo.getServiceName()), SysJob::getServiceName, bo.getServiceName());
        lqw.eq(StringUtils.isNotBlank(bo.getServiceMethod()), SysJob::getServiceMethod, bo.getServiceMethod());
        lqw.eq(StringUtils.isNotBlank(bo.getCronExpression()), SysJob::getCronExpression, bo.getCronExpression());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysJob::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增定时任务
     *
     * @param bo 查询条件
     * @param bo Job信息
     * @return 定时任务列表
     * @return
     */
    @Override
    public Boolean insertByBo(SysJobBo bo) {
        SysJob add = MapstructUtils.convert(bo, SysJob.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setJobId(add.getJobId());
        }
        return flag;
    }

    /**
     * 修改定时任务
     *
     * @param bo Job信息
     * @return 定时任务是否修改成功
     */
    @Override
    public Boolean updateByBo(SysJobBo bo) {
        SysJob update = MapstructUtils.convert(bo, SysJob.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;

    }

    /**
     * 校验并批量删除Job信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据ServiceName和serviceMethod获取Cron表达式
     *
     * @param methodName 定时任务方法
     * @return Cron表达式
     */
    @Override
    public String getJobCron(String methodName, String serviceName, String serviceMethod) {
        if (StringUtils.isBlank(serviceName) || StringUtils.isBlank(methodName) || StringUtils.isBlank(serviceMethod)) {
            return INVALID_CRON;
        }
        // 获取对应的Service实例
        Object service = applicationContext.getBean(serviceName);
        // 使用反射来检查serviceMethod是否存在于指定的Service类中
        if (!isMethodExists(service, serviceMethod)) {
            log.error("方法{}不存在于Service {}", serviceMethod, serviceName);
            return INVALID_CRON;
        }
        // 重置旧 methodName 的状态（与 serviceName/serviceMethod 关联）
        jobStatusServiceImpl.resetPreviousMethodStatus(methodName, serviceName, serviceMethod);
        // 获取并更新当前方法状态
        SysJob job = jobStatusServiceImpl.updateCurrentMethodStatus(methodName, serviceName, serviceMethod);
        if (job == null) {
            log.error("未找到methodName为{}的任务", methodName);
            return INVALID_CRON;
        }
        this.cronExpression = job.getCronExpression();
        taskScheduler.startScheduledTask(cronExpression, serviceName, serviceMethod);
        return cronExpression;
    }

    /**
     * 检查service中是否存在指定的serviceMethod方法
     *
     * @param service       服务实例
     * @param serviceMethod 方法名称
     * @return 是否存在
     */
    private boolean isMethodExists(Object service, String serviceMethod) {
        try {
            // 获取服务类的字节码
            Class<?> serviceClass = service.getClass();
            // 获取所有方法并检查指定方法是否存在
            for (Method method : serviceClass.getDeclaredMethods()) {
                if (method.getName().equals(serviceMethod)) {
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("检查方法是否存在时出错", e);
        }
        return false;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysJob entity) {
        //TODO 做一些数据校验,如唯一约束
    }
}
